package com.owen.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageInfo;
import com.owen.pojo.Interview;
import com.owen.pojo.Vegetables;
import com.owen.server.InterviewServer;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 采访
 */
@Controller
@RequestMapping(value = "/interview")
public class InterviewController extends BaseController {

    @Autowired
    private InterviewServer interviewServer;

    @RequestMapping(value = "/list")
    public ModelAndView list(Interview interview,
                             @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                             ModelAndView modelAndView) {
        // 查询数据
        PageInfo<Interview> interviewPageInfo = interviewServer.findByInterview(interview, pageNum, pageSize);
        modelAndView.addObject("data", interviewPageInfo);
        modelAndView.setViewName("interview/list");
        return modelAndView;
    }

    /**
     * 详情
     *
     * @param id
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public ModelAndView details(@RequestParam(name = "id") Integer id,
                                ModelAndView modelAndView) {
        Interview interview = interviewServer.findById(id);
        modelAndView.addObject("interview", interview);
        modelAndView.setViewName("interview/details");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping(value = "/fileExport")
    public void fileExport(Interview interview, HttpServletResponse response) throws ClassNotFoundException, IndexOutOfBoundsException, IOException {
        // 生成excel
        ExcelWriter writer = ExcelUtil.getWriter();
        // 数据库查询
        List<Interview> byInterview = interviewServer.findByMedium(interview);

//
//

        StyleSet style = writer.getStyleSet();
        Font font = writer.createFont();
//        font.setColor(IndexedColors.VIOLET.index);
        font.setBold(true);
        font.setFontHeightInPoints((short) 20);
        //重点，设置中文字体
        font.setFontName("楷体");

        style.getHeadCellStyle().setFont(font);

        style.setBackgroundColor(IndexedColors.WHITE, true);


        // Title
        int columns = Class.forName("com.owen.pojo.Interview").getDeclaredFields().length;
        ExcelWriter title = writer.merge(columns - 6, "新闻媒体采访信息");

        // Header
        ExcelWriter a = writer.addHeaderAlias("id", "编号");
        ExcelWriter b = writer.addHeaderAlias("medium", "媒体");
        ExcelWriter c = writer.addHeaderAlias("col", "栏目");
        ExcelWriter d = writer.addHeaderAlias("reporter", "记者");
        ExcelWriter e = writer.addHeaderAlias("phone", "联系方式");
        ExcelWriter f = writer.addHeaderAlias("theme", "采访主题");
        ExcelWriter g = writer.addHeaderAlias("interviewTime", "采访时间");
        ExcelWriter h = writer.addHeaderAlias("address", "地点");
        ExcelWriter i = writer.addHeaderAlias("demand", "采访需求");
        ExcelWriter j = writer.addHeaderAlias("target", "采访对象");
        ExcelWriter k = writer.addHeaderAlias("opinion", "意见");
        ExcelWriter l = writer.addHeaderAlias("leaderOpinion", "领导批示");
        ExcelWriter m = writer.addHeaderAlias("result", "承办结果");

        writer.setColumnWidth(0, 20);
        writer.setColumnWidth(1, 20);
        writer.setColumnWidth(2, 20);
        writer.setColumnWidth(3, 20);
        writer.setColumnWidth(4, 20);
        writer.setColumnWidth(5, 20);
        writer.setColumnWidth(6, 20);
        writer.setColumnWidth(7, 20);
        writer.setColumnWidth(8, 20);
        writer.setColumnWidth(9, 20);
        writer.setColumnWidth(10, 20);
        writer.setColumnWidth(11, 20);
        writer.setColumnWidth(12, 20);


        List<Map<String, Object>> rows = byInterview.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", item.getId() == null ? "" : item.getId().toString());
            maps.put("medium", item.getMedium());
            maps.put("col", item.getCol());
            maps.put("reporter", item.getReporter());
            maps.put("phone", item.getPhone());
            maps.put("theme", item.getTheme());
            maps.put("interviewTime", item.getInterviewTime());
            maps.put("address", item.getAddress());
            maps.put("target", item.getTarget());
            maps.put("demand", item.getDemand());
            maps.put("opinion", item.getOpinion());
            maps.put("leaderOpinion", item.getLeaderOpinion());
            maps.put("result", item.getResult());
            return maps;
        }).collect(Collectors.toList());

        writer.write(rows, true);

        a.setRowHeight(0, 45);
        b.setRowHeight(1, 45);
        c.setRowHeight(2, 45);
        d.setRowHeight(3, 45);
        e.setRowHeight(4, 45);
        f.setRowHeight(5, 45);
        g.setRowHeight(6, 45);
        h.setRowHeight(7, 45);
        i.setRowHeight(8, 45);
        j.setRowHeight(9, 45);
        k.setRowHeight(10, 45);
        l.setRowHeight(11, 45);
        m.setRowHeight(12, 45);
        title.setRowHeight(0, 70);

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("新闻媒体采访信息-" + DateUtil.today() + ".xlsx", "utf-8"));
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }


    @RequestMapping(value = "/saveAndEdit", method = RequestMethod.GET)
    public ModelAndView saveAndEdit(@RequestParam(name = "id", defaultValue = "0") Integer id,
                                    ModelAndView modelAndView) {
        if (id != 0) {
            Interview interview = interviewServer.findById(id);
            modelAndView.addObject("interview", interview);
        }
        modelAndView.setViewName("interview/saveAndEdit");
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping(value = "/saveAndEdit", method = RequestMethod.POST)
    public String saveAndEdit(Interview interview) {
        Map<String, Object> map = new HashMap<>();
        if (interview != null) {
            Integer id = interview.getId();
            if (id == null) {
                Integer save = interviewServer.save(interview);
                if (save > 0) {
                    map.put("code", "200");
                    map.put("msg", "添加成功");
                }
            } else {
                Integer update = interviewServer.update(interview);
                if (update > 0) {
                    map.put("code", "200");
                    map.put("msg", "修改成功");
                }
            }
        }
        return JSON.toJSONString(map);
    }


    @ResponseBody
    @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.DELETE)
    public String deleteById(@PathVariable(name = "id") Integer id) {
        Map<String, Object> map = new HashMap<>();
        Integer del = interviewServer.deleteById(id);
        if (del > 0) {
            map.put("code", "200");
            map.put("msg", "操作成功");
        } else {
            map.put("code", "500");
            map.put("msg", "操作失败");
        }
        return JSON.toJSONString(map);
    }

    /**
     * 下载文档
     *
     * @param id
     */
    @RequestMapping(value = "/downloadDocx/{id}", method = RequestMethod.GET)
    public void downloadDocx(@PathVariable(name = "id") Integer id, HttpServletResponse response) throws Exception {
        interviewServer.downloadDocx(id, response);
    }

    @ResponseBody
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    public String deleteBatch(Integer[] ids) {
        Map<String, Object> map = new HashMap<>();
        Integer del = interviewServer.deleteBatch(ids);
        if (del > 0) {
            map.put("code", "200");
            map.put("msg", "操作成功");
        } else {
            map.put("code", "500");
            map.put("msg", "操作失败");
        }
        return JSON.toJSONString(map);
    }


}
